<template>
  <div class="staff">
    <div class="form-top">
      <i class="el-icon-menu"></i>
      <span class="form-title">
          基本信息
      </span>
    </div>
    <el-form  :model="formLabel" label-width="150px" :inline="true" :rules="rules" ref="formLabel">
      <div class="left100">
        <el-col :span="12">
          <el-form-item label="保险公司：" class="is-required" prop="company">
            <el-select v-model="formLabel.company" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in formLabel.companies" :key="item.id" :value="item.id" :label="item.insuranceName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码：" class="is-required" prop="pwd">
            <el-input v-model="formLabel.pwd" placeholder="请填写密码" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="机构代码：">
            <el-input v-model="formLabel.mech" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="VPN地址：">
            <el-input v-model="formLabel.vpnadd" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="VPN登录密码：">
            <el-input v-model="formLabel.vpnpwd" placeholder="" size="small"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="IP地址：">
            <el-input v-model="formLabel.ipadd" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="出单平台锁定登录：">
            <el-select v-model="formLabel.plat" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in formLabel.status" :key="item.value" :value="item.isActive" :label="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input v-model="formLabel.phone" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工号："  class="is-required" prop="number">
            <el-input v-model="formLabel.number" placeholder="请填写工号" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="工号描述："  class="is-required" prop="describe">
            <el-input v-model="formLabel.describe" placeholder="请填写工号描述" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="formLabel.state" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in formLabel.status" :key="item.value" :value="item.isActive" :label="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="VPN登录名：">
            <el-input v-model="formLabel.vpnname" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="Mac地址：">
            <el-input v-model="formLabel.macadd" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="机器码：">
            <el-input v-model="formLabel.mechnumber" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="使用录单：">
            <el-select v-model="formLabel.list" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in formLabel.status" :key="item.value" :value="item.isActive" :label="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='24'>
          <el-form-item label="工号所属区域：" class="offsetR is-required" prop="area">
            <!-- <el-select v-model="formLabel.provice" placeholder="请选择省" size="mini" class="wd180 ma20" @change="cities">
              <el-option v-for="item in formLabel.provices" :key="item.key"  :value="item.key" :label="item.value">
              </el-option>
            </el-select>
            <el-select v-model="formLabel.city" placeholder="请选择市" size="mini" class="wd180 ma20" @change="areas">
              <el-option v-for="item in formLabel.cities" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
            <el-select v-model="formLabel.area" placeholder="请选择区（县）" size="mini" class="wd180 ma20" @change="zui">
              <el-option v-for="item in formLabel.areas" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select> -->
            <el-cascader
              :options="options2"
              @active-item-change="handleItemChange"
              @change='getAreaId'
              :props="props"
              v-model="formLabel.area"
              size='mini'
              class='wd230'
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span='24'>
          <el-form-item label="关联组织：" class="offsetR toBlock is-required org" prop="orgs">
            <div style="width:770px">
              <span class="setColor" @click="openTree = true" v-for="org in formLabel.orgs" v-if="formLabel.orgs">{{org.fullName}}</span>
              <span class="setColor" @click="openTree = true" v-for="tree in treename" v-if="treename">{{tree}}</span>
            </div>
            <el-button size="mini" @click="openTree = true" class="toBlock"><i class="iconfont icon-organization"></i>&nbsp;{{formLabel.org}}</el-button>
            <div class="hiddenInput">
            <el-input type="hidden"  v-model="formLabel.orgs"></el-input>
            </div>
            <el-dialog title="选择组织" :visible.sync="openTree" width='500px'>
              <div class="fix">
                <el-tree
                  :data="organizationUnitTree"
                  show-checkbox
                  node-key="id"
                  :default-expanded-keys="[1,3,12,8,9,13,16,12,14]"
                  :default-checked-keys="treeArr"
                  :props="defaultProps"
                  ref="tree"
                 >
                </el-tree>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button @click="openTree = false">取 消</el-button>
                <el-button type="primary"  @click="getCheckedKeys()">确 定</el-button>
              </div>
            </el-dialog>
          </el-form-item>
          <el-form-item label="备注信息：" class="offsetR toBlock">
            <el-input
              type="textarea"
              :autosize="{minRows:3}"
              placeholder="请输入内容"
              v-model="formLabel.textarea" style="width:730px">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span='24'>
          <el-row class="center">
            <el-button type="primary" size="small" @click="submitForm('formLabel')">保存</el-button>
            <el-button type="info" size="small">取消</el-button>
          </el-row>
        </el-col>
      </div>
    </el-form>
  </div>


</template>
<script>
export default {
  data() {
    return {
      organizationUnitTree: [],
      openTree: false,
      formLabel: {
        // 区域
        area:'',
        // 公司
        company: '',
        // 公司数据
        companies: [],
        // 状态
        status: [{
          isActive: true,
          value: '正常'
        }, {
          isActive: false,
          value: '禁用'
        }],
        // 省
        provice: '',
        // 省数据
        provices: [],
        // 市
        city: '',
        // 市数据
        cities: [],
        // 区
        area: '',
        // 区数据
        areas: [],
        // 工号
        number: '',
        // 密码
        pwd: '',
        // 机构
        mech: '',
        // 描述
        describe: '',
        // vpn 地址
        vpnadd: '',
        // VPN 名字
        vpnname: '',
        // 备注
        textarea: '',
        // 出单平台
        plat: '',
        // 录单
        list: '',
        // 组织
        org: '选择组织',
        // VPN 密码
        vpnpwd: '',
        // ip 地址
        ipadd: '',
        // 手机号
        phone: '',
        // mac地址
        macadd: '',
        // 机器码
        mechnumber: ''
      },
      defaultProps: {
        children: 'organizationUnits',
        label: 'displayName'
      },
      //级联
      options2:[],
      props: {
          value: 'key',
          label:'value',
          children: 'children'
      },
      rules: {
        company: [{ required: true, message: '请输入保险公司', trigger: 'change' }],
        pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        number: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        describe: [{ required: true, message: '请输入工号描述', trigger: 'blur' }],
        area: [{ required: true, message: '请选择完整的区域', trigger: 'change' }],
        orgs: [{ type: 'array', required: true, message: '请至少选择一个组织', trigger: 'change' }]
      },
      from: false, // 来自哪里，false为新建，true为更新
      treename:[],
      treeArr:[]
    }
  },
  mounted() {
    console.log('------------')
    this.id = this.$route.params.id
    console.log(this.id)
    if (this.id != 0) {
      this.getInfo()
      this.from = true
    }
    this.getTree()
    this.companies()
    this.provices()
  },
  methods: {
    // 级联
    handleItemChange(val){
      console.warn(val);
      const that = this;
      // console.warn(val.length);
      if(val.length == 1){
        this.getCities(val);
      }else 
      if(val.length == 2){
        this.getAreas(val);
      }
    },
    getAreaId(val){
      // console.warn(val);
      this.formLabel.regionId = val[val.length-1];
      console.warn(this.formLabel.regionId);
    },
      //得到权限集合
      treearray(data) {
        // console.log(data)
        var treeArr = [];
        var treeNames = [];
        data.map(function (item) {
          if (item.isCheck) {
            treeArr.push(item.id)
            treeNames.push(item.fullName)
          }
          if (item.organizationUnits  .length > 0) { //遍历2级
            item.organizationUnits .map(function (elem) {
              if (elem.isCheck) {
                treeArr.push(elem.id)
                treeNames.push(elem.fullName)
              }
              /*if (elem.organizationUnits .length > 0) { //遍历3级
                elem.organizationUnits .map(function (obj) {
                  if (obj.isCheck ) {
                    treeArr.push(obj.id)
                    treeNames.push(obj.fullName)
                  }

                  if (obj.organizationUnits .length > 0) { //遍历4级
                    obj.organizationUnits .map(function (last) {
                      if (last.isCheck ) {
                        treeArr.push(last.id)
                        treeNames.push(last.fullName)
                      }
                      //遍历3级
                    })
                  }
                })
              }*/
            })
          }
        })
        return {treeArr,treeNames};
      },
    // 详细
    getInfo() {
      const that = this
      const params = {
        id: this.id
      }
      this.post(params, 'services/app/staff/GetStaffDetail').then(rs => {
        // console.log('-------------')
        // console.log(rs)
        if (rs.success) {
          that.from = true
          that.formLabel.company = rs.result.staff.insuranceId
          that.formLabel.describe = rs.result.staff.describe
          that.formLabel.provice = rs.result.staff.regionIds.provinceId
          that.formLabel.city = rs.result.staff.regionIds.cityId
          that.formLabel.area = rs.result.staff.regionIds.areaId
          that.formLabel.pwd = rs.result.staff.staffPassword
          that.formLabel.vpnpwd = rs.result.staff.vpnPassword
          that.formLabel.number = rs.result.staff.staffAccount
          that.formLabel.phone = rs.result.staff.phoneNumber
          that.formLabel.ipadd = rs.result.staff.ip
          that.formLabel.mech = rs.result.staff.insuranceCode
          that.formLabel.vpnadd = rs.result.staff.vpnAddress
          that.formLabel.vpnname = rs.result.staff.vpnAccount
          that.formLabel.macadd = rs.result.staff.mac
          that.formLabel.mechnumber = rs.result.staff.machineCode
          that.formLabel.textarea = rs.result.staff.remark
          that.formLabel.state = rs.result.staff.isActive
          that.formLabel.plat = rs.result.staff.isSystemLocked
          that.formLabel.list = rs.result.staff.isRecord

          // 树
          console.log('///////////////////-------');

          that.treeArr = that.treearray(rs.result.organizationUnitTree ).treeArr;
          that.treename = that.treearray(rs.result.organizationUnitTree ).treeNames
          console.log(that.treeArr)
          console.log(that.treename)
        }
      })
    },
    // 树
    getTree() {
      const params = []
      this.post(params, 'services/app/common/GetOrganizationUnits').then(rs => {
        // console.log('-----------')
        // console.log(rs)
        if (rs.success) {
          this.organizationUnitTree = rs.result
          // console.log(this.organizationUnitTree)
        }
      })
    },
    // 验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit')
          this.save()
        } else {
          console.log('error submit')
          return false
        }
      })
    },
    // 公司
    companies() {
      const that = this
      const params = {}
      this.post(params, 'services/app/common/GetInsurances').then(rs => {
        console.log(rs)
        if (rs.success) {
          that.formLabel.companies = rs.result.items
        }
      })
    },
    // 省
    provices() {
      const that = this
      const params = {}
      this.post(params, 'services/app/Common/GetRegions').then(rs => {
        console.log(rs.result)
        console.log('----------------');
        if (rs.success) {
          for(let i=0;i<rs.result.items.length;i++){
            rs.result.items[i].children = [];
          }
          that.formLabel.provices = rs.result.items
          that.options2 = rs.result.items;
          // console.log(that.options2);
        }
      })
    },
    // 市
    cities(val) {
      const that = this
      console.log(val)
      const params = {
        id: val[0]
      }
      this.post(params, 'services/app/Common/GetRegions').then(rs => {
        console.log(rs.result)
        console.log('//////////111111111')
        if (rs.success) {
            for(let i=0;i<rs.result.items.length;i++){
              rs.result.items[i].children = [];
            }
            let provice = that.formLabel.provices
            provice.forEach(item => {
              if(item.key == val[0]){
                item.children = rs.result.items;
              }
            })
            that.options2 = provice;  // 省，市
            that.formLabel.cities = rs.result.items
        }
      })
    },
    // 区
    areas(val) {
      const that = this
      console.log(val)
      const params = {
        id: val[1]
      }
      this.post(params, 'services/app/Common/GetRegions').then(rs => {
        console.log(rs.result)
        if (rs.success) {
            let city = that.formLabel.cities
            let provice = that.formLabel.provices
            city.forEach(item => {
              if(item.key == val[1]){
                item.children = rs.result.items; //市，区
              }
            })
            provice.forEach(p=>{
              if(p.key == val[0]){
                p.children = city;
              }
            })
            that.options2 = provice
            console.log(that.options2);
            that.formLabel.areas = rs.result.items
        }
      })
    },
    zui(val) {
      this.area = val
    },
    // 树值
    getCheckedNodes() {
      // console.log(this.$refs.tree.getCheckedNodes())
      this.formLabel.orgs = this.$refs.tree.getCheckedNodes()
    },
    getCheckedKeys() {
      this.openTree = false
      // console.log(this.$refs.tree.getCheckedKeys())
      this.getCheckedNodes()
      this.treeSelect = this.$refs.tree.getCheckedKeys()
    },
    // 保存
    save() {
      const that = this
      if (!this.from) {
        console.log('走创建')
        // 创建接口的参数
        const staffadd = {
          insuranceId : this.formLabel.company,
          staffAccount: this.formLabel.number, // 工号
          staffPassword: this.formLabel.pwd, // 密码
          describe: this.formLabel.describe, // 工号描述
          vpnPassword: this.formLabel.vpnpwd, // VPN登录密码
          ip: this.formLabel.ipadd, // IP地址
          insuranceCode: this.formLabel.mech, // 机构代码
          vpnAddress: this.formLabel.vpnadd, // VPN地址
          vpnAccount: this.formLabel.vpnname, // VPN登录名
          mac: this.formLabel.macadd, // mac地址
          machineCode: this.formLabel.mechnumber, // 机器码
          phoneNumber: this.formLabel.phone, // 手机号
          insuranceId: this.formLabel.company, // 保险公司
          regionId: this.formLabel.regionId
        }
        const paramsadd = {
          OrganizationUnitIds: this.treeSelect, // 组织树
          staff: staffadd
        }
        console.warn(paramsadd)
        // 判断走创建是不是选了组织权限
        if (paramsadd.OrganizationUnitIds) {
          that.post(paramsadd, 'services/app/staff/CreateStaff').then(rs => {
            console.log(rs)
            if (rs.success) {
              console.log('成功-----------')
              this.$router.push({
                name: 'staffdetail'
              })
            }
          })
        } else {
          console.log('error----------')
        }
      } else {
        console.log('走编辑')
        // 编辑接口的参数
        const staffd = {
          id: this.id,
          insuranceId : this.formLabel.company,
          staffAccount: this.formLabel.number, // 工号
          staffPassword: this.formLabel.pwd, // 密码
          describe: this.formLabel.describe, // 工号描述
          vpnPassword: this.formLabel.vpnpwd, // VPN登录密码
          ip: this.formLabel.ipadd, // IP地址
          insuranceCode: this.formLabel.mech, // 机构代码
          vpnAddress: this.formLabel.vpnadd, // VPN地址
          vpnAccount: this.formLabel.vpnname, // VPN登录名
          mac: this.formLabel.macadd, // mac地址
          machineCode: this.formLabel.mechnumber, // 机器码
          phoneNumber: this.formLabel.phone, // 手机号
          insuranceId: this.formLabel.company, // 保险公司
          regionId: this.formLabel.regionId
        }
        const params = {
          OrganizationUnitIds: this.treeSelect, // 组织树
          staff: staffd
        }
        // console.log(params)
        // 判断是不是选了组织权限
        if (params.OrganizationUnitIds) {
          that.post(params, 'services/app/staff/UpdateStaff').then(rs => {
            // if(as.success){
            //   this.stateSvc.go('home.announce')
            //   console.log('编辑成功')
            // }else{
            //   console.log('编辑失败')
            // }
            // this.stateSvc.go('home.announce')
            console.log(rs)
            if (rs.success) {
              console.log('成功------------')
              this.$router.push({
                name: 'staffdetail'
              })
            }
          })
        } else {
          console.log('error------------')
        }
      }
    }

  }
}
</script>
<style lang="scss" scoped>
  .left100{
    margin:15px 100px 0 120px;
  }
  .fix{
    min-height: 300px;
    overflow-y: auto;
    margin-left:100px;
  }
  .el-row{
    padding:20px;
  }
  .center{
    text-align: center;
  }
  .offsetR{
    
  }
  .toBlock{
    display:block;
  }
  .org>.el-form-item__content{
    width:770px;
  }
  .ma20{
    margin-right: 20px;
  }
  .el-form-item.is-required .el-form-item__label:before{
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .setColor{
    color: #333;
    border-radius: 5px;
    background-color: #efefef;
    padding: 5px;
    border: 1px solid #d7d7d7;
    margin:0 20px 10px 0;
    display: inline-block;
    line-height:10px;
  }
  .hiddenInput{
    width:400px;
    height:0;
  }
  .wd230{
    width: 230px;
  }
  .staff{
    padding:25px;
  }
  .form-top{
      width: 100%;
      overflow: hidden;
      position: relative;
    .i{
      font-size:15px;
    }

    .form-title{
      font-size: 16px;
      color: #555;
    }
  }
  .form-top:after{
    display: block;
    height: 1px;
    width: 100%;
    position: absolute;
    left:103px;
    top:10px;
    background: #ddd;
    content: '';
  }
</style>
